package com.frinder.netty.time;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by kiktech on 2017/8/3.
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 在连接被建立并且准备进行通信时被调用
     *
     * @param ctx
     */
    @Override
    public void channelActive(final ChannelHandlerContext ctx) { // (1)
        final ByteBuf time = ctx.alloc().buffer(4); // (2)
        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));
        System.out.println(time.toString());
        final ChannelFuture f = ctx.writeAndFlush(time); // (3)
//        f.addListener(future -> {
//            assert f == future;
//            ctx.close();
//        }); // (4)
        f.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}